<?php
// 在文件开头添加安全限制（防止直接访问）
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Method Not Allowed');
}

header('Content-Type: text/plain'); // 保持流式传输
header('X-Accel-Buffering: no');    // 禁用Nginx缓冲
ob_implicit_flush(true);            // 实时输出缓冲

// 从环境变量获取API Key（安全！）
$apiKey = getenv('DEEPSEEK_API_KEY');
$apiUrl = 'https://api.deepseek.com/v1/chat/completions';

// 获取请求数据
$postData = json_decode(file_get_contents('php://input'), true);
$userMessage = $postData['message'];
$history = $postData['history'] ?? [];

// 构建请求数据
$data = [
    'model' => 'deepseek-chat',
    'messages' => array_merge($history, [['role' => 'user', 'content' => $userMessage]]),
    'temperature' => 0.7,
    'stream' => true
];

// 初始化cURL
$ch = curl_init($apiUrl);
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . $apiKey,
        'Content-Type: application/json',
        'Accept: text/event-stream' // 重要：声明接受流式响应
    ],
    CURLOPT_POSTFIELDS => json_encode($data),
    CURLOPT_WRITEFUNCTION => function($ch, $data) {
        // 处理流式数据块
        $lines = explode("\n", $data);
        foreach ($lines as $line) {
            if (strpos($line, 'data: ') === 0) {
                $json = substr($line, 6);
                if ($json === '[DONE]') break;
                
                $response = json_decode($json, true);
                if (isset($response['choices'][0]['delta']['content'])) {
                    echo $response['choices'][0]['delta']['content'];
                    ob_flush();
                    flush();
                }
            }
        }
        return strlen($data); // 必须返回处理的数据长度
    }
]);

// 执行请求
$response = curl_exec($ch);
if (curl_errno($ch)) {
    echo "⚠️ API请求错误: " . curl_error($ch);
}
curl_close($ch);
?>